<?php
session_start();

require_once 'securimage/securimage.php';

class Authentic {

    /**
     *
     * @var <type>
     */
    static private $User;

    /**
     *
     * @var <type>
     */
    static private $Pass;

    /**
     *
     * @var <type>
     */
    static private $TokenSess;

    /**
     *
     * @var <type>
     */
    static private $TokenCook;

    /**
     *
     * @var <type>
     */
    private $dbSql;

    /**
     *
     * @var <type>
     */
    private $url = null;

    /**
     *
     */
    public function  __construct() {

        $this->url = "http://{$_SERVER['SERVER_NAME']}/sms/sisLogin.php";

        if($_POST['log_usuario_sis'] && $_POST['pwd_usuario_sis']){
            $img = new Securimage();
            $valid = $img->check($_POST['code']);

            if($valid != true){
                die("<script>alert('Código incorreto! Tente novamente.');window.location='" . $this->url . "'</script>");
            }
            
            $this->autheSet($_POST['log_usuario_sis'], md5($_POST['pwd_usuario_sis']));
            $this->autheSql();
        } else if($_SESSION['LOG_USUARIO'] && $_SESSION['PWD_USUARIO']){
            $this->autheSet($_SESSION['LOG_USUARIO'], $_SESSION['PWD_USUARIO']);
            $this->autheSql();

            self::$TokenCook = $_SESSION['tokensess'];
            self::$TokenSess = $_SESSION['tokensess'];
            
        } else if($_REQUEST['logout']){
            $this->autheLogout();
        } else {
            die(utf8_decode("<script>alert('Por favor, informe o usuário e senha!');window.location='" . $this->url . "'</script>"));
        }

        if($_SESSION['tokensess'] != $_COOKIE['tokencook']){
            /*die("<script>alert('Token false::: Por favor, informe o usuário e senha!');window.location='../sisLogin.php'</script>");*/
        } else {
            self::$TokenCook = 1477460779;
            self::$TokenSess = self::$TokenCook;
            
            //setcookie("tokencook", base64_encode(self::$TokenCook), time()+3600);
            //$_SESSION['tokensess'] = base64_encode(self::$TokenSess);
        }
    }

    /**
     *
     */
    public function  __destruct() {
        self::$User = null;
        self::$Pass = null;
        self::$TokenSess = null;
        self::$TokenCook = null;
    }

    /**
     *
     * @param <type> $userSet
     * @param <type> $passSet
     * @param <type> $tokenSess
     * @param <type> $tokenCook
     */
    private function autheSet($userSet, $passSet, $tokenSess=null, $tokenCook=null){
        if($_POST || $_COOKIE){
            self::$User = $userSet;
            self::$Pass = $passSet;
            self::$TokenSess = $tokenSess;
            self::$TokenCook = $tokenCook;
        }
    }

    /**
     *
     */
    private function autheSql(){

        if(!empty(self::$User) && !empty(self::$Pass)){
            $this->dbSql = new Deia_Model("cad_usuario");
            $qwy = $this->dbSql->prepare("
                SELECT
                    U.cod_usuario,
                    U.cod_grupo_usuario,
                    U.nom_usuario,
                    U.log_usuario,
                    U.pwd_usuario,
                    U.pais_usuario,
                    S.qtd_sms
                FROM cad_usuario U
                INNER JOIN sms_usuario S ON S.cod_usuario = U.cod_usuario
                WHERE
                    U.log_usuario = ?
                    AND U.pwd_usuario = ?"
            );

            if($qwy->execute(array(self::$User, self::$Pass))){
                $row = $qwy->fetch(PDO::FETCH_ASSOC);
                if(self::$User == $row['log_usuario'] && self::$Pass == $row['pwd_usuario']){
                    $_SESSION['COD_USUARIO'] = $row['cod_usuario'];
                    $_SESSION['NOM_USUARIO'] = $row['nom_usuario'];
                    $_SESSION['LOG_USUARIO'] = $row['log_usuario'];
                    $_SESSION['PWD_USUARIO'] = $row['pwd_usuario'];
                    $_SESSION['GRP_USUARIO'] = $row['cod_grupo_usuario'];
                    $_SESSION['PAIS_USUARIO'] = $row['pais_usuario'];
                    $_SESSION['QTD_SMS'] = $row['qtd_sms'];
                    $_SESSION['DAT_USUARIO'] = date("d/m/Y H:i:s");

                } else {
                    die("<script>alert('Usuário ou senha inválida!');window.location='" . $this->url . "'</script>");
                }
            }
        } else {
            die("<script>alert('Informe o usuário e a senha!');window.location='" . $this->url . "'</script>");
            //header("Location: sisLogin.php");
        }
    }

    /**
     * 
     */
    private function autheLogout(){
        setcookie("log_usuario_sis", "");
        setcookie("pwd_usuario_sis", "");
        unset($_SESSION['tokensess']);

        die("<script>window.location='" . $this->url . "';</script>");
    }
}

$authentc = new Authentic();